<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>修改密码</span>
    </div>
    <div class="text item">
      <el-form label-width="100px" :model="updatePwd" ref="form" :rules="pwdRules">
        <el-form-item label="原密码" prop="old_pwd">
          <el-input type="password" show-password v-model="updatePwd.old_pwd"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input type="password" show-password v-model="updatePwd.new_pwd"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="re_pwd">
          <el-input type="password" show-password v-model="updatePwd.re_pwd"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateUser">确认修改</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { updatePwdAPI } from '@/api/user'
export default {
  name: 'UserPwd',
  data() {
    const rePwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value !== this.updatePwd.new_pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const newPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else if (value === this.updatePwd.old_pwd) {
        callback(new Error('新密码和原密码不能一样!'))
      } else {
        callback()
      }
    }
    return {
      updatePwd: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      pwdRules: {
        old_pwd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: newPwd, trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: rePwd, trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updateUser() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const { data: res } = await updatePwdAPI(this.updatePwd)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$refs.form.resetFields()
          this.$store.commit('user/updateToken', '')
          this.$store.commit('user/getUser', {})
          this.$router.push('/login')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    reset() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 450px;
}
</style>
